package main

import (
	"net"
	"net/http"
	"sync"
)

var kv = make(map[string]string)
var mutex sync.RWMutex

func main() {
	http.HandleFunc("/", func(writer http.ResponseWriter, r *http.Request) {
		var ip string
		ip = r.Header.Get("X-Real-IP")
		if ip == "" {
			ip = r.Header.Get("X-Forwarded-For")
		}
		if ip == "" {
			ip, _, _ = net.SplitHostPort(r.RemoteAddr)
		}
		writer.Write([]byte(ip))
	})

	http.HandleFunc("/kv", func(w http.ResponseWriter, r *http.Request) {
		k := r.URL.Query().Get("k")
		v := r.URL.Query().Get("v")
		if k == "" {
			return
		}
		if v == "" {
			mutex.RLock()
			v = kv[k]
			mutex.RUnlock()
			w.Write([]byte(v))
			return
		}
		mutex.Lock()
		kv[k] = v
		mutex.Unlock()
	})

	http.ListenAndServe(":8002", nil)
}
